package study.thread.collection;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/*
 * 生产者--消费者问题：生产者往阻塞队列中放入字符串，消费者从阻塞队列里移除字符串
 * 
 */
public class BlockingQueueDemon {

	public static void main(String[] args) {
		//阻塞队列
		BlockingQueue<String> queue = new ArrayBlockingQueue<String>(5);

		Producer p = new Producer(queue);

		Consumer c1 = new Consumer(queue);
		Consumer c2 = new Consumer(queue);

		new Thread(p).start();
		new Thread(c1).start();
		new Thread(c2).start();
	}
}

class Consumer implements Runnable {
	//由数组支持的有界队列
	private final BlockingQueue<String> queue;

	Consumer(BlockingQueue<String> q) {
		queue = q;
	}

	public void run() {
		try {
			for (int i = 0; i < 100; i++) {
				//阻塞队列的take()操作会在队列中没有任何东西可拿时阻塞
				String temp = consume(queue.take());
				System.out.println(Thread.currentThread().getName()+"consume " + temp+" num ==> "+i+" ArrayBlockingQueue: "+queue.size());
			}
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
	}

	String consume(String x) {
		//
		return x;
	}
}

class Producer implements Runnable {
	//由数组支持的有界队列
	private final BlockingQueue<String> queue;

	Producer(BlockingQueue<String> q) {
		queue = q;
	}

	public void run() {
		try {
			for (int i = 0; i < 100; i++) {
				String temp = produce();
				//阻塞队列的put()操作会在没有空间可用时阻塞
				queue.put(temp);
				//System.out.println("produce " + temp+" num ==> "+i+" ArrayBlockingQueue: "+queue.size());
			}
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
	}

	String produce() {
		String temp = "" + (char) ('A' + (int) (Math.random() * 26));
		return temp;
	}
}
